import os
from pathlib import Path
from .counter_uvm_test import *
import cocotb
from pyuvm import *
from cocotb.clock import Clock
from cocotb.triggers import Timer, RisingEdge

# tests/tb_top.py
import cocotb
from pyuvm import uvm_root

async def run_test():
    """直接运行测试用例"""
    await uvm_root().run_test("Testcase_0")
    
    # 确保足够时间写入波形
    await cocotb.triggers.Timer(1000, "ns")
    cocotb.log.info("测试正常结束")

@cocotb.test()
async def cocotb_entry(dut):
    """Cocotb 测试入口点"""
    cocotb.log.info("启动 UVM 测试")
    await run_test()
    cocotb.log.info("UVM 测试完成")

@pyuvm.test()
class Testcase_0(uvm_test):
    def build_phase(self):
        self.env = CounterEnv("env", self)
    async def run_phase(self):
        self.raise_objection()
        # 打印仿真参数
        dut = cocotb.top
        params = ""
        for i, arg in enumerate(dut._args):
            params += f"argv[{i}] = {arg}\n"
        self.logger.info(f"仿真运行参数:\n{params}")
        # 添加足够延迟确保波形写入
        await Timer(100, "ns")
        # 1. 设置时钟和复位
        dut = cocotb.top
        # 创建时钟 - 使用正确的信号名
        clock = Clock(dut.clk, 10, units="ns")
        cocotb.start_soon(clock.start(start_high=False))
        # 复位序列
        dut.rst_n.value = 0
        await Timer(20, "ns")
        dut.rst_n.value = 1
        await Timer(10, "ns")
        
        # 2. 启动测试序列
        seq = CounterSequence.create("seq")
        await seq.start(self.env.agent.seqr)
        self.drop_objection()